#include "log.h"

void writeLog(const char* format, ...)
{
    va_list ap;
    va_start(ap, format);

#ifndef UNDER_CE
    char buf[1024];
    vsprintf_s(buf, 1024, format, ap);
    if (buf[strlen(buf) - 1] != '\n') {
        strcat(buf, "\n");
    }
    OutputDebugStringA(buf);
#else

    if (!logfile_inited)
    {
        return;
    }

    struct tm* info = currenttime();
    char buf[1024];

    sprintf(buf, "[%02d/%02d/%04d %02d:%02d:%02d] ",
        info->tm_mon,
        info->tm_mday,
        info->tm_year,
        info->tm_hour,
        info->tm_min,
        info->tm_sec);

    vsprintf(buf, format, ap);
    if (buf[strlen(buf) - 1] != '\n') {
        strcat(buf, "\n");
    }
    fputs(buf, logfile);

    // Who can wait for it to flush when fclose!!
    fflush(logfile);

#endif
    va_end(ap);
}

void initlog()
{
    // #ifndef UNDER_CE
    logfile = stdout;
    // #else
    //     struct tm* info = currenttime();
    //     char buf[64] = {0};
    //
    //     sprintf_s(buf, 64, "\\NAND\\log\\%02d-%02d-%04d.log",
    //               info->tm_mon,
    //               info->tm_mday,
    //               info->tm_year);
    //     fopen_s(&logfile, buf, "a");
    // #endif

    logfile_inited = true;
}

struct tm* currenttime()
{
    static struct tm s_tm = {0};
    static SYSTEMTIME s_systm = {0};

    ::GetSystemTime(&s_systm);

    s_tm.tm_year = s_systm.wYear;
    s_tm.tm_mon = s_systm.wMonth;
    s_tm.tm_mday = s_systm.wDay;
    s_tm.tm_wday = s_systm.wDayOfWeek;
    s_tm.tm_hour = s_systm.wHour;
    s_tm.tm_min = s_systm.wMinute;
    s_tm.tm_sec = s_systm.wSecond;

    return &s_tm;
}

void closeLogfile()
{
    if (!logfile_inited)
    {
        return;
    }

    if (logfile != stdout)
    {
        fclose(logfile);
    }

    logfile_inited = false;
}
